package com.tanger.user;

import com.tanger.common.exception.ServiceException;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import com.tanger.common.utils.StringUtil;
import com.tanger.flowable.api.FlowAbleFactory;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author Hchenbin
 * @Date 2022/7/28 16:14
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository repository;
    @Autowired
    private BaseUserRepository userRepository;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;

    @Override
    public List<User> findAll() {
        return Optional.ofNullable(repository.findAll()).orElse(new ArrayList<>());
    }

    @Override
    public User findUserByCreateDate(Long startTime, Long endTime) {
        return Optional.ofNullable(repository.findByCreateDateBetween(startTime,endTime))
                .map(users -> users.get(0))
                .orElseGet(null);
    }

    @Override
    public List<UserEntity> queryAll() {
        UserEntity user = new UserEntity();
        user.setStatus(1);
        Example<UserEntity> example = Example.of(user);
        return Optional.ofNullable(userRepository.findAll(example))
                .map(s -> s.stream()
                        .filter(userEntity -> userEntity.getDelFlag().equals(0))
                        .collect(Collectors.toList()))
                .orElse(Collections.emptyList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult deleteByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids))
            return ActionResult.buildResultError("参数缺失");
        userRepository.deleteAllById(ids);
        return ActionResult.buildResultSuccess("success");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult updateStatus(Long id, Integer status) {
        if (StringUtil.isNull(id) || StringUtil.isNull(status))
            return ActionResult.buildResultError("参数缺失");
        UserEntity user = new UserEntity();
        user.setId(id);
        user.setStatus(status);
        userRepository.save(user);
        return ActionResult.buildResultSuccess("success");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult add(UserEntity user) {
        userRepository.save(user);
        return ActionResult.buildResultSuccess("success");
    }

    @Override
    public UserEntity findOne(Long id) {
        return userRepository.findById(id).orElseThrow(() -> new ServiceException("不存在"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult update(UserEntity user) {
        UserEntity orgUser = findOne(user.getId());
        orgUser = BeanUtils.copyProperties(user,orgUser);
        userRepository.save(orgUser);
        return ActionResult.buildResultSuccess("success");
    }

    @Override
    public String submit(Map map, String flowId) {
//        map.put("day", 5);//请假天数
//        map.put("applyUser", "小明");
        // leave为员工请假流程xml文件中的id
        ProcessInstance a1 = runtimeService.startProcessInstanceByKey(flowId, map);

        Task task = taskService.createTaskQuery().processInstanceId(a1.getId()).singleResult();
        taskService.complete(task.getId());
        return task.getProcessInstanceId();
    }

    @Override
    public List<Task> findAll(String roleCode) {
        return Optional.ofNullable(
                    taskService.createTaskQuery().taskCandidateGroup(roleCode))
                .map(v -> v.list())
                .orElseGet(Collections::emptyList);
    }

    @Override
    public ActionResult complate(String flowId, Integer isPass) {
        Map<String,Object> map = new HashMap<>();
        map.put("outcome", isPass.intValue() == 1? "通过":"驳回");
        Task task = taskService.createTaskQuery().processInstanceId(flowId).singleResult();
        taskService.complete(task.getId(), map);
        return ActionResult.buildResultSuccess("OK");
    }
}
